<template>
	<view>

		<view class="uni-header">


			<view class="uni-group">
				<view class="uni-title"></view>
				<view class="uni-sub-title"></view>
			</view>
			<view class="uni-group">

				<input class="uni-search" type="number" v-model="sid_min" placeholder="开始题目ID" />
				<input class="uni-search" type="number" v-model="sid_max" placeholder="结束题目ID" />
				<button @click="searchQues">搜索题目</button>

				<input class="uni-search" type="text" v-model="query" @confirm="search" placeholder="请输入搜索内容" />
				<!-- <button class="uni-button" type="default" size="mini" @click="search">搜索</button> -->
				<button class="uni-button" type="default" size="mini" @click="navigateTo('./add')">新增</button>
				<button class="uni-button" type="default" size="mini" @click="getAllJYDTData">获取全部有记忆导图的题目</button>
				<button class="uni-button" type="default" size="mini" :disabled="!selectedIndexs.length"
					@click="delTable">批量删除</button>
				<download-excel class="hide-on-phone" :fields="exportExcel.fields" :data="exportExcelData"
					:type="exportExcel.type" :name="exportExcel.filename">
					<button class="uni-button" type="primary" size="mini">导出 Excel</button>
				</download-excel>

				<button class="uni-button" type="primary" size="mini" @click="uploadExcel">导入 Excel</button>
				<!-- <button class="uni-button" type="primary" size="mini" @click="updateField">导入记忆导图</button> -->
			</view>
		</view>
		<view class="uni-container">
			<unicloud-db ref="udb" :collection="collectionList"
				field="s_id,q_type,q_desc,q_struct,q_ans,img,video,sound,auto_sound,q_analyse,key_word" :where="where"
				page-data="replace" :orderby="orderby" :getcount="true" :page-size="options.pageSize"
				:page-current="options.pageCurrent" v-slot:default="{data,pagination,loading,error,options}"
				:options="options" loadtime="manual" @load="onqueryload">
				<uni-table ref="table" :loading="loading" :emptyText="error.message || '没有更多数据'" border stripe
					type="selection" @selection-change="selectionChange">
					<uni-tr>
						<uni-th align="center" filter-type="search" @filter-change="filterChange($event, 's_id')"
							sortable @sort-change="sortChange($event, 's_id')">题目编号</uni-th>
						<uni-th align="center" filter-type="select" :filter-data="options.filterData.q_type_localdata"
							@filter-change="filterChange($event, 'q_type')">题型</uni-th>
						<uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'q_desc')"
							sortable @sort-change="sortChange($event, 'q_desc')">题目介绍</uni-th>
						<uni-th align="center" sortable @sort-change="sortChange($event, 'q_struct')">题目选项</uni-th>
						<uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'q_ans')"
							sortable @sort-change="sortChange($event, 'q_ans')">题目答案</uni-th>
						<uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'img')"
							sortable @sort-change="sortChange($event, 'img')">试题图片</uni-th>
						<uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'video')"
							sortable @sort-change="sortChange($event, 'video')">试题视频讲解</uni-th>
						<uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'sound')"
							sortable @sort-change="sortChange($event, 'sound')">视频音频讲解</uni-th>
						<uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'auto_sound')"
							sortable @sort-change="sortChange($event, 'auto_sound')">试题读题语音</uni-th>
						<uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'q_analyse')"
							sortable @sort-change="sortChange($event, 'q_analyse')">试题文字解析</uni-th>
						<uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'key_word')"
							sortable @sort-change="sortChange($event, 'key_word')">关键字</uni-th>
						<uni-th align="center">操作</uni-th>
					</uni-tr>
					<uni-tr v-for="(item,index) in data" :key="index">
						<uni-td align="center">{{item.s_id}}</uni-td>
						<uni-td align="center">{{options.q_type_valuetotext[item.q_type]}}</uni-td>
						<uni-td align="center">{{item.q_desc}}</uni-td>
						<uni-td align="center">

							<uni-tag style="display: block;" :text="struct_item.value" :type="typeArr[s_index]"
								v-for="(struct_item , s_index) in item.q_struct" :key="struct_item.id">

							</uni-tag>

						</uni-td>
						<uni-td align="center">{{item.q_ans}}</uni-td>
						<uni-td align="center">{{item.img}}</uni-td>
						<uni-td align="center">{{item.video}}</uni-td>
						<uni-td align="center">{{item.sound}}</uni-td>
						<uni-td align="center">{{item.auto_sound}}</uni-td>
						<uni-td align="center">{{item.q_analyse}}</uni-td>
						<uni-td align="center">{{item.key_word}}</uni-td>
						<uni-td align="center">
							<view class="uni-group">
								<button @click="navigateTo('./edit?id='+item._id, false)" class="uni-button" size="mini"
									type="primary">修改</button>
								<button @click="confirmDelete(item._id)" class="uni-button" size="mini"
									type="warn">删除</button>
							</view>
						</uni-td>
					</uni-tr>
				</uni-table>
				<view class="uni-pagination-box">
					<view>
						<uni-tag text="10" @click="changePageSize(10)"></uni-tag>
						<uni-tag text="50" @click="changePageSize(50)"></uni-tag>
						<uni-tag text="100" @click="changePageSize(100)"></uni-tag>
						<uni-tag text="500" @click="changePageSize(500)"></uni-tag>
						<uni-tag text="1000" @click="changePageSize(1000)"></uni-tag>
					</view>
					<uni-pagination :page-size="pagination.size" v-model="pagination.current" :showIcon="true"
						:total="pagination.count" @change="onPageChanged" />
				</view>
			</unicloud-db>
		</view>
	</view>
</template>

<script>
	import {
		enumConverter,
		filterToWhere
	} from '@/js_sdk/validator/quesction.js';

	// import * as SSF from "ssf";
	import * as XLSX from '@/js_sdk/xlsx/dist/xlsx.full.min.js'



	const db = uniCloud.database()
	// 表查询配置
	const dbOrderBy = 'sid asc' // 排序字段
	const dbSearchFields = [] // 模糊搜索字段，支持模糊搜索的字段列表。联表查询格式: 主表字段名.副表字段名，例如用户表关联角色表 role.role_name
	// 分页配置
	const pageSize = 20
	const pageCurrent = 1

	const orderByMapping = {
		"ascending": "asc",
		"descending": "desc"
	}

	export default {
		data() {
			return {
				sid_min: 0,
				sid_max: 0,
				cachedata: [],
				typeArr: ['primary', 'success', 'warning', 'error', 'royal', 'default'],
				collectionList: "quesction",
				query: '',
				where: '',
				orderby: dbOrderBy,
				orderByFieldName: "",
				selectedIndexs: [],
				options: {
					pageSize,
					pageCurrent,
					filterData: {
						"q_type_localdata": [{
								"value": 0,
								"text": "单选"
							},
							{
								"value": 1,
								"text": "多选"
							},
							{
								"value": 2,
								"text": "判断"
							}
						]
					},
					...enumConverter
				},
				imageStyles: {
					width: 64,
					height: 64
				},
				exportExcel: {
					"filename": "quesction.xls",
					"type": "xls",
					"fields": {
						"题目编号": "s_id",
						"题型": "q_type",
						"题目介绍": "q_desc",
						"题目选项": "q_struct",
						"题目答案": "q_ans",
						"试题图片": "img",
						"试题视频讲解": "video",
						"试题音频讲解": "sound",
						"试题读题语音": "auto_sound",
						"试题文字解析": "q_analyse",
						"关键字": "key_word",
						"语种": "lang_txt",
						"记忆导图": "q_rember",
						"分类课程": "q_catesub",
					},
					"updateFields": {
						"记忆导图": "q_rember",
						"分类课程": "q_catesub",
						"题目编号": "s_id"
					}
				},
				exportExcelData: [],
				q_type_map: {},
				u_q_type_map: {}
			}
		},
		onLoad() {
			this._filter = {}
			this.q_type_map = new Map()
			this.q_type_map.set(0, '单选')
			this.q_type_map.set(1, '多选')
			this.q_type_map.set(2, '判断')
			console.log(this.q_type_map.get(0))
			this.u_q_type_map = new Map()
			this.u_q_type_map.set('单选', 0)
			this.u_q_type_map.set('多选', 1)
			this.u_q_type_map.set('判断', 2)

		},
		onReady() {
			this.$refs.udb.loadData()
			// this.sortAll()
			// this.getAllData()
			// this.getAllJYDTData()
		},
		methods: {

			async getAllJYDTData() {
				uni.showLoading()

				const self = this
				this.exportExcelData = []
				const allData = []
				const responseTotal = await db.collection('quesction').where({
					q_rember: db.command.neq(null)
				}).count()
				const size = responseTotal.result.total
				// const size = 10
				if (size > 0) {
					let total = size
					let processSize = 0
					let position = 1
					let allData = []
					while (processSize < total) {
						const responseData = await db.collection('quesction').where({
							q_rember: db.command.neq(null)
						}).skip(processSize).limit(500).get()
						if (responseData.result.data.length > 0) {

							responseData.result.data.forEach(e => {

								let r_q_type = self.q_type_map.get(e.q_type)
								let r_q_struct = []
								for (let struct of e.q_struct) {
									r_q_struct.push(struct.value)
								}
								e.q_type = r_q_type
								e.q_struct = r_q_struct.join('|')
								self.exportExcelData.push(e)

							})
							console.log(self.exportExcelData.length)

						}
						processSize += responseData.result.data.length
					}

				}


				uni.hideLoading()
			},

			async getAllData() {
				uni.showLoading()
				const self = this
				const allData = []
				const responseTotal = await db.collection('quesction').count()
				const size = responseTotal.result.total
				// const size = 10
				if (size > 0) {
					let total = size
					let processSize = 0
					let position = 1
					let allData = []
					while (processSize < total) {
						const responseData = await db.collection('quesction').skip(processSize).limit(500).get()
						if (responseData.result.data.length > 0) {

							responseData.result.data.forEach(e => {

								let r_q_type = self.q_type_map.get(e.q_type)
								let r_q_struct = []
								for (let struct of e.q_struct) {
									r_q_struct.push(struct.value)
								}
								e.q_type = r_q_type
								e.q_struct = r_q_struct.join('|')
								self.exportExcelData.push(e)

							})
							console.log(self.exportExcelData.length)

						}
						processSize += responseData.result.data.length
					}

				}


				uni.hideLoading()
			},
			async sortAll() {
				const collection = db.collection('quesction')
				let size = await collection.count()
				size = size.result.total
				let index = 0
				let datalist = []
				let notSidallSize = 0
				console.log('all size', size)
				while (index < size) {
					const d = await collection
						.field({
							_id: true,
							s_id: true,
							sid: true
						})
						.skip(index)
						.limit(500).get()
					index += d.result.data.length
					if (d.result.data.length > 0) {
						for (let s of d.result.data) {
							if (s.sid && s.sid > 0) {
								continue
							} else {
								notSidallSize++
								s.sid = Number(s.s_id)
								datalist.push(s)
							}

						}
					}
				}
				console.log('notSidallSize', notSidallSize, datalist.length)
				for (let i = 0; i < datalist.length; i++) {
					let {
						sid
					} = datalist[i]
					await collection.where({
						_id: datalist[i]._id
					}).update({
						sid
					})
				}
			},
			changePageSize(pagesize) {
				this.$set(this.options, 'pageSize', pagesize)
				this.$nextTick(() => {
					this.$refs.udb.loadData()
				})
			},
			onqueryload(data) {
				this.exportExcelData = []
				let list = this.$cloneObject(data)
				//console.log(list)
				for (let s of list) {
					let r_q_type = this.q_type_map.get(s.q_type)
					let r_q_struct = []
					for (let struct of s.q_struct) {
						r_q_struct.push(struct.value)
					}
					s.q_type = r_q_type
					s.q_struct = r_q_struct.join('|')
					this.exportExcelData.push(s)
				}
				console.log(this.exportExcelData.length)


				//	console.log(this.exportExcelData)
				//	console.log('data', data)
				return data

			},
			getWhere() {
				const query = this.query.trim()
				if (!query) {
					return ''
				}
				const queryRe = new RegExp(query, 'i')
				return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ')
			},
			searchQues() {
				const where = {
					sid: db.command.gte(Number(parseInt(this.sid_min))).and(db.command.lte(parseInt(this.sid_max)))
				}
				this.where = where
				console.log(this.where)
				this.$nextTick(() => {
					this.loadData()
				})
			},
			search() {
				const newWhere = this.getWhere()
				this.where = newWhere
				this.$nextTick(() => {
					this.loadData()
				})
			},
			loadData(clear = true) {
				this.$refs.udb.loadData({
					clear
				})
			},
			onPageChanged(e) {
				this.selectedIndexs.length = 0
				this.$refs.table.clearSelection()
				this.$refs.udb.loadData({
					current: e.current
				})
			},
			navigateTo(url, clear) {
				// clear 表示刷新列表时是否清除页码，true 表示刷新并回到列表第 1 页，默认为 true
				uni.navigateTo({
					url,
					events: {
						refreshData: () => {
							this.loadData(clear)
						}
					}
				})
			},
			// 多选处理
			selectedItems() {
				var dataList = this.$refs.udb.dataList
				return this.selectedIndexs.map(i => dataList[i]._id)
			},
			// 批量删除
			delTable() {
				this.$refs.udb.remove(this.selectedItems(), {
					success: (res) => {
						this.$refs.table.clearSelection()
					}
				})
			},
			// 多选
			selectionChange(e) {
				this.selectedIndexs = e.detail.index
			},
			confirmDelete(id) {
				this.$refs.udb.remove(id, {
					success: (res) => {
						this.$refs.table.clearSelection()
					}
				})
			},
			sortChange(e, name) {
				this.orderByFieldName = name;
				if (e.order) {
					this.orderby = name + ' ' + orderByMapping[e.order]
				} else {
					this.orderby = ''
				}
				this.$refs.table.clearSelection()
				this.$nextTick(() => {
					this.$refs.udb.loadData()
				})
			},
			filterChange(e, name) {
				this._filter[name] = {
					type: e.filterType,
					value: e.filter
				}
				let newWhere = filterToWhere(this._filter, db.command)
				if (Object.keys(newWhere).length) {
					this.where = newWhere
				} else {
					this.where = ''
				}
				this.$nextTick(() => {
					this.$refs.udb.loadData()
				})
			},
			updateField() {
				const self = this
				uni.showLoading()

				uni.chooseFile({
					async success(res) {
						const url = res.tempFilePaths[0];
						const data = await (await fetch(url, {
							mode: 'no-cors'
						})).arrayBuffer();
						/* data is an ArrayBuffer */
						const workbook = XLSX.read(data);
						const xlsxData = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]])
						let keyMap = Object.keys(self.exportExcel.updateFields)
						let importData = []
						for (let s of xlsxData) {
							let d = {}
							for (let t of keyMap) {
								d[self.exportExcel.updateFields[t]] = s[t]
								if (self.exportExcel.updateFields[t] == 's_id') {
									d[self.exportExcel.updateFields[t]] = s[t].toString()
									d.sid = s[t]
								}
							}
							importData.push(d)
						}

						for (let i = 0; i < importData.length; i++) {
							await db.collection('quesction').where({
								s_id: importData[i].s_id
							}).update(importData[i]).then((res) => {
								return true
							}).catch((err) => {
								console.log(err)
								uni.showModal({
									content: err.message,
									showCancel: false
								})
							})
						}

						uni.hideLoading()
					}
				})
			},
			uploadExcel() {
				const self = this
				uni.showLoading()

				uni.chooseFile({
					async success(res) {
						const url = res.tempFilePaths[0];
						const data = await (await fetch(url, {
							mode: 'no-cors'
						})).arrayBuffer();
						/* data is an ArrayBuffer */
						const workbook = XLSX.read(data);
						const xlsxData = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]])
						let keyMap = Object.keys(self.exportExcel.fields)
						let importData = []
						for (let s of xlsxData) {
							let d = {}
							for (let t of keyMap) {

								d[self.exportExcel.fields[t]] = s[t]

								//更换数据类型 q_type mapping
								if (self.exportExcel.fields[t] == 'q_type') {
									d[self.exportExcel.fields[t]] = self.u_q_type_map.get(s[t])
								}

								if (self.exportExcel.fields[t] == 's_id') {
									console.log(s[t])
									d[self.exportExcel.fields[t]] = s[t].toString()
									d.sid = s[t]
								}

								if (self.exportExcel.fields[t] == 'q_struct') {

									let q_str_arr = s[t].split("|")
									let q_d_struct = []
									for (let id = 0; id < q_str_arr.length; id++) {
										q_d_struct.push({
											index: id,
											value: q_str_arr[id]
										})
									}
									d[self.exportExcel.fields[t]] = q_d_struct
								}


							}
							importData.push(d)
						}

						console.log(importData)
						await db.collection('quesction').add(importData).then((res) => {
							uni.showToast({
								title: '新增成功'
							})
						}).catch((err) => {
							console.log(err)
							uni.showModal({
								content: err.message,
								showCancel: false
							})
						})

						uni.hideLoading()

						// console.log(workbook.Sheets[workbook.SheetNames[0]])
						/* DO SOMETHING WITH workbook HERE */

					}
				})

			}
		}
	}
</script>

<style>


</style>
